import { stringifyExpression } from '@vue/compiler-core'
import { defineStore } from 'pinia'

interface Token {
  access_token: string
  // token_type:string
  // refresh_token:string
  // expires_in:number
  // user_id:string
}

export const useTokenStore = defineStore('usertoken', () => {
  //ref相当于state
  const tokenJson = ref('')
  //computed相当于getter
  const token = computed<Token>(() => {
    try {
      return JSON.parse(tokenJson.value || window.localStorage.getItem('Usertoken') || '{}')
    } catch (err) {
      ElMessage.error('josn字符串格式不对,转化对象是时失败...')
      //防止window.localStorage下次再次报错，设置成空
      window.localStorage.setItem('Usertoken', '')
      throw err
    }
  })
  //function相当于actions
  function saveToken(data: string) {
    tokenJson.value = data
    window.localStorage.setItem('Usertoken', data)
  }

  return { token, saveToken }
})
